import { Effect, ImmerReducer } from 'umi';
interface ObjKey {
  [key: string]: string;
}

export interface ExampleModelState {
  name: string;
  secondName: string;
}

export interface ExampleModelType {
  namespace: 'todo';
  state: ExampleModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    save: ImmerReducer<ExampleModelState & ObjKey>;
  };
}

const ExampleModel: ExampleModelType = {
  namespace: 'todo',

  state: {
    name: 'todo list title from dva',
    secondName: 'secondName',
  },

  effects: {
    *query({ payload }, { call, put }) {
      const res = yield call(callFun, 'query');
      console.log(res, 'res');
      yield put({ type: 'save', payload: { secondName: payload } });
    },
  },

  reducers: {
    save(state: ExampleModelState & ObjKey, action) {
      const { payload } = action;
      console.log(payload, 'payloadpayloadpayload');
      Object.keys(payload).map((key: string) => {
        state[`${key}`] = payload[key];
      });
    },
  },
};

function callFun<T>(query: T) {
  return new Promise((resolve) => {
    console.log(query, 'callFunQuery');
    setTimeout(() => {
      resolve('callFun');
    }, 2000);
  });
}

export default ExampleModel;
